<template>
  <div :id="id" :style="{ height: height, width: width }"></div>
</template>

<script>
export default {
  props: {
    id: String, //图表id
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    schoolname_list: Array,
    area_list: Array,
  },
  data() {
    return {
      chart: null,
      dataarr: [],
      windowWidth: document.documentElement.clientWidth,
    };
  },
  watch: {
    area_list: {
      handler() {
        if (this.chart != null && this.chart != "" && this.chart != undefined) {
          this.dataarr = [];
          for (let i = 0; i < this.schoolname_list.length; i++) {
            let obj = {
              value: this.area_list[i],
              name: this.schoolname_list[i],
            };
            this.dataarr.push(obj);
          }
          let option = this.chart.getOption();
          // console.log("ssssssssssss", option);
          option.series[0].data = this.dataarr;
          this.chart.setOption(option);

          // this.chart.dispose();
        } else {
          // 真正在页面上显示图表的是下面这一行
          for (let i = 0; i < this.schoolname_list.length; i++) {
            let obj = {
              value: this.area_list[i],
              name: this.schoolname_list[i],
            };
            this.dataarr.push(obj);
            this.drawRing();
            console.log("aaa");
          }
        }
      },
      deep: true,
    },
  },
  mounted() {
    // 下面那一行加了也不起作用，因为父子生命周期的原因，所以还没有数据
    // this.drawRing();
  },
  beforeDestroy() {
    //销毁chart
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    drawRing() {
      // 基于准备好的dom，初始化echarts实例
      this.chart = this.$echarts.init(document.getElementById(this.id), null, {
        renderer: "svg",
      });
      // 绘制图表
      this.chart.setOption({
        title: {
          text: "占地面积",
          left: "center",
          textStyle: {
            fontSize: 10,
          },
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          top: "5%",
          orient: "vertical",
          left: "left",
          textStyle: {
            color: "black",
            fontSize: 10,
          },
          itemGap: 4,
          itemWidth: 10,
          itemHeight: 8,
        },
        series: [
          {
            name: "占地面积",
            type: "pie",
            center: ["60%", "60%"],
            radius: "65%",
            data: this.dataarr,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              show: false,
            },
          },
        ],
      });
    },
  },
};
</script>
